package dk.modified.reshary;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import dk.modified.reshary.GlobalState.TrackerName;

public class ShowOwnerShares extends Activity {

	ListView listView;
	ArrayList<Owners> ownerArrList;
	final int ACTIVITY_VIEW_PAGER = 1337;
	private Boolean isFavorite = false;
	private Owners clickedOwner;
	private int clickedPosition;
	ShowOwnerSharesAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_show_owner_shares);
		Tracker t = ((GlobalState) getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		t.setScreenName("Reshary Show Shares List");
		t.send(new HitBuilders.AppViewBuilder().build());
		getActionBar().setDisplayHomeAsUpEnabled(true);
		String title = getIntent().getExtras().getString("title");
		Util.setActionBar(this, title);

		listView = (ListView) findViewById(R.id.listview);
		ownerArrList = new ArrayList<Owners>();
		if(getIntent().getExtras().containsKey("favorite")){
			ShowFavoritesPost();
			isFavorite = true;
		} else {
			ShowOwnerSharesPost(getIntent().getExtras().getString("ownerid"));
		}

		SetOnItemClickListener();

	}

	private void SetOnItemClickListener() {
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Bundle bundle = new Bundle();
				bundle.putString("title", getIntent().getExtras().getString("title"));
				bundle.putInt("position", position);
				if(getIntent().getExtras().containsKey("favorite")){
					bundle.putBoolean("favorite", true);
				}
				bundle.putParcelableArrayList("arraylist", ownerArrList);
				Intent intent = new Intent(getApplicationContext(),
						ViewOwnerShare.class);
				intent.putExtras(bundle);
				startActivityForResult(intent, ACTIVITY_VIEW_PAGER);
				overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			listView.setSelection(data.getExtras().getInt("position"));
		}
		
		super.onActivityResult(requestCode, resultCode, data);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	
	private void ShowFavoritesPost(){
		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("securitytoken", securitytoken);
		params.put("userid", userid);

		ResharyRestClient.post("favorite_shares/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						super.onFailure(arg0, arg1, arg2, arg3);
						Toast.makeText(
								getApplicationContext(),
								getResources()
										.getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
						finish();
					}

					@Override
					public void onSuccess(String content) {

						if (!content.equals("null")) {
							Map<String, Object> postResponse = Util
									.specialformatResponse(content);

							if (postResponse.containsKey("error")) {

							} else {

								@SuppressWarnings("unchecked")
								ArrayList<Object> arrOfShares = (ArrayList<Object>) postResponse
										.get("share");

								for (int i = 0; i < arrOfShares.size(); i++) {

									@SuppressWarnings("unchecked")
									Map<String, String> share = (Map<String, String>) arrOfShares
											.get(i);

									String ownername = postResponse.get(
											"realname").toString();
									String id = share.get("id");
									String filename = share.get("filename");
									String videoFilename = null;
									if (share.containsKey("streamurl")) {
										videoFilename = share.get("streamurl");
									}
									String thumbnail = share.get("thumbnail");
									String sharingurl = share.get("sharingurl");
									String shares = share.get("shares");
									String dateadded = share.get("dateadded");
									String mediatitle = share.get("title");

									int mediaState = Integer.parseInt(share
											.get("mediatype"));
									Owners owner = new Owners(id, filename,
											videoFilename, thumbnail,
											sharingurl, shares, dateadded,
											ownername, mediatitle, mediaState);

									ownerArrList.add(owner);
								}

								adapter = new ShowOwnerSharesAdapter(
										ShowOwnerShares.this,
										R.layout.ownershare_listview_item,
										ownerArrList);
								listView.setAdapter(adapter);
								registerForContextMenu(listView);
							}

						} else {
							Toast.makeText(
									getApplicationContext(),
									getResources()
											.getString(R.string.no_shares),
									Toast.LENGTH_LONG).show();
							finish();
						}

					}

				}, this);
	}
	
	
	
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.fadeout,
				R.anim.fadein);
	}

	private void ShowOwnerSharesPost(String ownerid) {

		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("ownerid", ownerid);
		params.put("securitytoken", securitytoken);
		params.put("userid", userid);

		ResharyRestClient.post("ownersshares/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						super.onFailure(arg0, arg1, arg2, arg3);
						Toast.makeText(
								getApplicationContext(),
								getResources()
										.getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
						finish();
					}

					@Override
					public void onSuccess(String content) {

						if (!content.equals("null")) {
							Map<String, Object> postResponse = Util
									.specialformatResponse(content);

							if (postResponse.containsKey("error")) {

							} else {

								@SuppressWarnings("unchecked")
								ArrayList<Object> arrOfShares = (ArrayList<Object>) postResponse
										.get("share");

								for (int i = 0; i < arrOfShares.size(); i++) {

									@SuppressWarnings("unchecked")
									Map<String, String> share = (Map<String, String>) arrOfShares
											.get(i);
									String ownername = postResponse.get(
											"realname").toString();
									String id = share.get("id");
									String filename = share.get("filename");
									String videoFilename = null;
									if (share.containsKey("streamurl")) {
										videoFilename = share.get("streamurl");
									}
									String thumbnail = share.get("thumbnail");
									String sharingurl = share.get("sharingurl");
									String shares = share.get("shares");
									String dateadded = share.get("dateadded");
									String mediatitle = share.get("title");

									int mediaState = Integer.parseInt(share
											.get("mediatype"));
									Owners owner = new Owners(id, filename,
											videoFilename, thumbnail,
											sharingurl, shares, dateadded,
											ownername, mediatitle, mediaState);

									ownerArrList.add(owner);
								}

								adapter = new ShowOwnerSharesAdapter(
										ShowOwnerShares.this,
										R.layout.ownershare_listview_item,
										ownerArrList);
								listView.setAdapter(adapter);
								registerForContextMenu(listView);
							}

						} else {
							Toast.makeText(
									getApplicationContext(),
									getResources()
											.getString(R.string.no_shares),
									Toast.LENGTH_LONG).show();
							finish();
						}

					}

				}, this);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);

		ListView lv = (ListView) v;
		AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;

		clickedOwner = (Owners) lv.getItemAtPosition(acmi.position);
		clickedPosition = acmi.position;
		
		MenuItem cmd_favorite = menu.findItem(R.id.cmd_favorite);
		if(isFavorite) cmd_favorite.setTitle(getString(R.string.context_favorite_remove));
		else cmd_favorite.setTitle(getString(R.string.context_favorite_add_or_remove));
		MenuItem cmd_save = menu.findItem(R.id.cmd_save);
		if(clickedOwner.getMediaState() == Owners.STATE_GIF) cmd_save.setTitle(getString(R.string.save_gif));
		else cmd_save.setTitle(getString(R.string.save_image));		
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		switch (item.getItemId()) {
		case R.id.cmd_favorite:
			if(isFavorite){
				RemoveFromFavorite(Integer.parseInt(clickedOwner.getId()));
				adapter.remove(clickedOwner);
			} else {
				AddToFavorite(Integer.parseInt(clickedOwner.getId()));
			}
			break;
		case R.id.cmd_save:
			if(clickedOwner.getMediaState() == Owners.STATE_GIF){
				DownloadGifBeforeSave(clickedOwner.getVideoFilename());
			} else {
				DownloadImageBeforeSave(clickedOwner.getFilename());
			}
			
		default:
			return super.onContextItemSelected(item);
		}
		return true;
	}
	
	
	public void AddToFavorite(int mediaId) {
		SharedPreferences sharedpreferences = getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("add_favorite/", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
								.show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.favorite_add);
						Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
								.show();
					}

				}, this);

	}

	public void RemoveFromFavorite(int mediaId) {
		SharedPreferences sharedpreferences = getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("rem_favorite/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
								.show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.favorite_remove);
						Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
								.show();
					}

				}, this);

	}
	
	private void DownloadGifBeforeSave(String filename) {
		
		final DownloadNotification notificationDownload = new DownloadNotification(this);
		notificationDownload.createNotification();

		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		ResharyRestClient.downloadImage(filename, null,
				new BinaryHttpResponseHandler(allowedContentTypes) {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {
						
						Toast.makeText(getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onProgress(int bytesWritten, int totalSize) {
					    int progressPercentage = (int)100*bytesWritten/totalSize;
					    if(progressPercentage % 5 == 0)
					    notificationDownload.setProgress(progressPercentage);
					}

					@Override
					public void onSuccess(byte[] binaryData) {
						notificationDownload.completed();
						File tempFile = Util.saveGif(binaryData);
						if (tempFile != null) {
							
							Bitmap tempBitmap = BitmapFactory.decodeByteArray(
									binaryData, 0, binaryData.length);
							SaveMediaNotification saveNotification = new SaveMediaNotification(
									getApplicationContext(), tempBitmap, clickedOwner
											.getMediaState(), Uri
											.fromFile(tempFile));
							saveNotification.createNotification();
						}
					}

				}, this, null);
	}
	private void DownloadImageBeforeSave(String filename){
		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		ResharyRestClient.downloadImage(filename, null,
				new BinaryHttpResponseHandler(allowedContentTypes) {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {
						
						Toast.makeText(getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}


					@Override
					public void onSuccess(final byte[] binaryData) {
						Runnable r = new Runnable() {
							@Override
							public void run() {
								
								Bitmap tempBitmap = BitmapFactory.decodeByteArray(
										binaryData, 0, binaryData.length);
								
								File tempFile = Util
										.saveImage(tempBitmap);
								if (tempFile != null) {
									SaveMediaNotification saveNotification = new SaveMediaNotification(
											getApplicationContext(),
											tempBitmap,
											clickedOwner.getMediaState(),
											Uri.fromFile(tempFile));
									saveNotification.createNotification();
								}
							}
						};
						new Thread(r).start();
					}

				}, this, null);
	}

}
